﻿{extend name="public:base" /}

{block name="css"}
<link rel="stylesheet" type="text/css" href="/static/layui/css/layui.css"/>
<link href="__ADMIN__/css/style.css" rel="stylesheet">
<style>
    #box {
        display: flex;
        justify-content: start;
    }

    h1 {
        text-align: center;
        color: #4a4a4a;
    }

    .container {
        max-width: 50%;
        margin: 0 auto;
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        padding: 20px;
        height: 79vh;
        overflow-y: scroll;
    }

    .container:last-child {
        margin-left: 20px;
    }

    .question {
        margin-bottom: 20px;
    }

    .question-title {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 10px;
        color: #333;
    }

    /* 单选题和多选题样式 */
    .options {
        list-style: none;
        padding: 0;
    }

    .options li {
        margin-bottom: 8px;
    }

    /* 填空题样式 */
    .input-readonly {
        width: 100%;
        padding: 10px;
        font-size: 16px;
        border-radius: 4px;
        border: 1px solid #ddd;
        margin-top: 5px;
        margin-bottom: 10px;
        background-color: #f9f9f9;
        color: #666;
        cursor: not-allowed;
    }

    .input {
        width: 100%;
        padding: 10px;
        font-size: 16px;
        border-radius: 4px;
        border: 1px solid #ddd;
        color: #666;
    }

    /* 问答题样式 */
    textarea {
        width: 100%;
        padding: 10px;
        font-size: 16px;
        border-radius: 4px;
        border: 1px solid #ddd;
        resize: vertical;
        min-height: 100px;
        background-color: #f9f9f9;
        color: #666;
        cursor: not-allowed;
    }

    /* 提交按钮样式 */
    button {
        background-color: #3a7bd5;
        color: white;
        padding: 8px 30px;
        border: none;
        border-radius: 4px;
        font-size: 14px;
        cursor: pointer;
        transition: background-color 0.3s ease;
    }

    .input-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
    }

    .input-box .del-rule {
        margin-left: 20px;
        background: red;
        color: #fff;
        border: none;
        padding: 11px 10px;
        border-radius: 4px;
        cursor: pointer;
        width: 100px;
        text-align: center;
    }

    /* 响应式设计 */
    @media (max-width: 600px) {
        .container {
            padding: 10px;
        }

        .question-title {
            font-size: 16px;
        }

        button {
            width: 100%;
        }
    }


    #optionsContainer {
        margin-top: 20px;
    }

    .layui-form-label {
        width: 200px;
        text-align: left;
    }

    .layui-input {
        display: block;
        width: calc(100% - 80px);
        padding-left: 10px;
    }

    .layui-input-block {
        margin-left: 120px;
    }

    .rule-set {
        display: flex;
        align-items: center;
        padding: 10px 0;
    }

    .rule-set strong {
        font-size: 16px;
        margin-right: 10px;
    }

    .row-rule {
        display: flex;
        justify-content: space-between;
    }

    #show_rules {
        display: flex;
        height: 40px;
        line-height: 40px;
        flex: 1;
        margin-right: 40px;
    }

    #show_rules .option {
        margin-right: 20px;
        font-size: 16px;
    }


</style>{/block}{block name="content"}

<div class="wrapper wrapper-content animated fadeInRight">
    <div id="box">
        <div class="container">
            <h1>{$info.title}</h1>

            {volist name="info.question" id="vo"}
            {if in_array($vo.type, [1,2,4])}
            <div class="question">
                <div class="question-title">{$vo.question}</div>
                <ul class="options">
                    {volist name="vo.answers" id="v"}
                    <li>{$v}</li>
                    {/volist}
                </ul>
            </div>
            {else}
            <div class="question">
                <div class="question-title">{$vo.question}</div>
                <input type="text" class="input-readonly" readonly>
            </div>
            {/if}
            {/volist}
        </div>

        <div class="container">
            <div class="question">
                <div class="question-title">问卷作答数量</div>
                <input type="number" class="input all_answer_count" min="1" placeholder="请输入问卷作答数量" value="{$info.all_answer_count}">
            </div>
            <div class="question">
                <div class="question-title">单套问卷作答时长（秒）</div>
                <input type="number" class="input single_answer_time" min="25" max="30" placeholder="请输入问卷作答时长（秒）" value="{$info.single_answer_time ? $info.single_answer_time : 25}">
            </div>
            <div class="layui-form">
                <div class="layui-form-item">
                    <label class="layui-form-label" style="padding: 9px 0;">选择题目</label>
                    <div class="layui-input-block">
                        <select id="questionSelect" lay-filter="questionSelect">
                            <option value="">请选择题目</option>
                            {volist name="info.question" id="vo" key="k"}
                            {if in_array($vo.type, [1,2,4])}
                            <option value="{$k}">{$vo.question}</option>
                            {/if}
                            {/volist}
                        </select>
                    </div>
                </div>

                <div id="optionsContainer"></div>

                <button class="layui-btn" onclick="saveRules()">保存规则</button>

                <div id="savedRulesContainer"></div>

            </div>

            <input type="hidden" class="id" value="{$info.id}">

            <button type="button" class="btn btn-w-m btn-primary" onclick="save()" style="width: 100%;margin-top: 10px">提交保存</button>
        </div>

    </div>


</div>

{/block}

{block name='js'}
<script src="/static/layui/layui.js"></script>

<script>
    var question = `{$question}` ? JSON.parse(`{$question}`) : [];  // 存储每道题的规则
    var savedRules = `{$user_rule}` ? JSON.parse(`{$user_rule}`) : [];  // 存储每道题的规则
    if (savedRules.length > 0) {
        renderSavedRules()
    }
    var singleRules = {questionIndex: -1, rule: []};// 用于验证概率纸盒是不是100；
    if (question.length > 0) {
        question.forEach((value, index) => {
            savedRules.push([])
        })
    }

    // 监听题目选择，动态生成选项输入框
    layui.use('form', function () {
        var form = layui.form;

        // 监听选择题目
        form.on('select(questionSelect)', function (data) {
            var questionIndex = parseInt(data.value) - 1;
            singleRules.questionIndex = questionIndex;
            singleRules.rule = [...savedRules[questionIndex]] || [];
            generateOptionInputs(questionIndex);
        });
    });

    function generateOptionInputs(questionIndex) {
        var $optionsContainer = $("#optionsContainer");
        $optionsContainer.empty();  // 清空之前的选项

        if (questionIndex == -1) {
            $('#questionSelect').val('');
            layui.form.render('select');
        }

        if (questionIndex == -1) {
            var optionCount = singleRules.rule;
        } else {
            var optionCount = question[questionIndex].answers.length;
        }


        for (var i = 0; i < optionCount; i++) {
            var value = savedRules[questionIndex][i] || '';  // 获取已保存的规则

            // 创建表单项并插入到页面
            var $formItem = $(
              `<div class="layui-form-item">
                <label class="layui-form-label" style="padding: 9px 0; white-space:nowrap;text-overflow:ellipsis;overflow:hidden;">${question[questionIndex].answers[i]}</label>
                <div class="layui-input-block">
                    <input type="number" class="layui-input" lay-filter="rule" data-question_index="${questionIndex}" data-option_index="${i}" placeholder="请输入概率" value="${value}">
                </div>
            </div>`
            );

            // 将表单项添加到容器中
            $optionsContainer.append($formItem);
        }

        // 重新渲染layui表单
        layui.form.render();
    }

    $(document).on('input', '[lay-filter="rule"]', function () {
        var value = $(this).val();
        var questionIndex = $(this).data('question_index');  // 获取 data-questionindex
        var optionIndex = $(this).data('option_index');      // 获取 data-optionindex

        value = parseFloat(value) ? parseFloat(value) : 0;

        var rule_len = singleRules.rule.length;
        var answers_len = question[questionIndex].answers.length;

        var rule_tmp = [];
        if (rule_len == 0) {
            for (var i = 0; i < answers_len; i++) {
                rule_tmp.push(0)
            }
            singleRules.rule = rule_tmp
        }

        singleRules.rule[optionIndex] = value
    });

    // 保存规则后展示功能
    function saveRules() {
        questionIndex = singleRules.questionIndex;
        if (questionIndex == -1) {
            layer.msg('请选择题目');
            return;
        }

        // 计算总概率，验证是否等于100%
        var total = singleRules.rule.reduce(function (acc, curr) {
            return acc + curr;
        }, 0);
        if (total !== 100) {
            layer.msg('各选项的概率之和必须等于100%，请重新设置');
            return;
        }

        savedRules[questionIndex] = singleRules.rule;

        // 展示已保存的规则
        renderSavedRules();
        generateOptionInputs(-1);
        singleRules = {questionIndex: -1, rule: []};
    }

    // 新增一个方法来渲染展示保存的规则
    function renderSavedRules() {
        var $rulesContainer = $('#savedRulesContainer');
        $rulesContainer.empty();  // 清空当前展示

        savedRules.forEach((ruleSet, questionIndex) => {
            if (ruleSet.length > 0) {
                var ruleDisplay = `<div class="rule-set"><strong>题目${questionIndex + 1}各选项概率:</strong>`;
                var option_html = '';
                ruleSet.forEach((rule, optionIndex) => {
                    option_html += `<div class="option">选项${optionIndex + 1}: ${rule}%</div>`;
                });
                $rulesContainer.append(ruleDisplay + `<div class="row-rule"><div id="show_rules">` + option_html + `</div><button class="layui-btn layui-btn-danger" onclick="deleteRules(${questionIndex})">删除</button></div></div>`);
            }
        });
    }

    // 删除整道题的规则
    function deleteRules(index) {
        if (index === -1) {
            layer.msg('请选择要删除规则的题目');
            return;
        }

        // 清空当前题目的规则
        savedRules[index] = [];

        // 重新生成选项输入框并展示
        generateOptionInputs(-1);
        renderSavedRules();
    }

    function save() {
        var all_answer_count = $('.all_answer_count').val(),
          single_answer_time = $('.single_answer_time').val(),
          user_rule_str = JSON.stringify(savedRules),
          id = $('.id').val();

        $.post('/admin/manage/setQuestionRule', {
            id, all_answer_count, single_answer_time, user_rule: user_rule_str
        }, res => {
            if (res.result == 1) {
                // 保存成功
                layer.msg(res.msg, {icon: 1, time: 1000}, function () {
                    window.location.href = '/admin/manage/questionList';
                })
            } else {
                layer.msg(res.msg, {icon: 2, time: 1000})
            }
        }, 'JSON')

    }

</script>{/block}
